import React, {useRef, useState} from 'react';
import {View, StyleSheet, ScrollView} from 'react-native';
import {useTranslation} from 'react-i18next';
import {userApi} from '@/services/api/userApi';
import Toast from '@/utils/toast';
import {ErrorText} from '@/components/ErrorText';
import {Controller, useForm} from 'react-hook-form';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {Button, TextInput, Icon, CodeTextInput} from 'tsun-smart-ui';
type RegisterFormData = {
  email: string;
  code: string;
  password: string;
  confirmPassword: string;
};
const ResetPasswordScreen = ({
  navigation,
}: ReactNavigation.RootStackScreenProps<'ResetPassword'>) => {
  const {t} = useTranslation();
  const {
    control,
    handleSubmit,
    formState: {errors},
    trigger,
    getValues,
    watch,
  } = useForm<RegisterFormData>({
    defaultValues: {
      email: '',
      code: '',
      password: '',
      confirmPassword: '',
    },
    mode: 'onChange',
  });
  const {bottom} = useSafeAreaInsets();
  const password = watch('password');
  const [loading, setLoading] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const btnRef = useRef<{
    setTargetDate: (date: number) => void;
  }>(null);
  const handleSendVerificationCode = async () => {
    // 验证邮箱格式
    const isValid = await trigger('email');
    if (!isValid) {
      return Promise.reject();
    }
    try {
      // 使用 userApi 发送验证码
      const email = getValues('email');
      btnRef.current?.setTargetDate(Date.now() + 3 * 60 * 1000);
      await userApi.sendResetPasswordCode(email);
      Toast.success({
        message: t('common.mail.code.send', {defaultValue: '验证码已发送'}),
      });
    } catch (error) {
      console.error('Send verification code error:', error);
      btnRef.current?.setTargetDate(void 0);
    }
  };

  const handleResetPassword = async () => {
    // 表单验证

    try {
      setLoading(true);
      // 使用 userApi 重置密码
      const {confirmPassword, ...resetParams} = getValues();

      await userApi.resetPassword(resetParams);

      Toast.success({
        message: t('common.editSuccessText', {
          defaultValue: '密码修改成功',
        }),
      });
      navigation.goBack();
    } finally {
      setLoading(false);
    }
  };

  return (
    <View
      style={[
        {
          paddingBottom: bottom + 27,
        },
      ]}
      className="px-4 flex-1">
      <ScrollView className="mt-4">
        {/* 邮箱输入 */}
        <View style={styles.inputGroup}>
          <Controller
            name="email"
            control={control}
            rules={{
              required: t('table.inputemailTip', {
                defaultValue: '请输入邮箱',
              }),
              pattern: {
                value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                message: t('mail.vail.tips', {
                  defaultValue: '请输入有效的邮箱地址',
                }),
              },
            }}
            render={({field: {onChange, value}}) => (
              <TextInput
                label={t('table.email', {defaultValue: '邮箱'})}
                left="email"
                placeholder={t('table.inputemailTip', {
                  defaultValue: '请输入邮箱',
                })}
                value={value}
                onChangeText={onChange}
                keyboardType="email-address"
                autoCapitalize="none"
              />
            )}
          />
          <View className="pt-2 ml-14">
            {errors.email && <ErrorText text={errors.email.message!} />}
          </View>
        </View>

        {/* 验证码输入 */}
        <View style={styles.inputGroup}>
          <Controller
            name="code"
            control={control}
            rules={{
              required: t('password.accountPlaceholder3', {
                defaultValue: '请输入验证码',
              }),
            }}
            render={({field: {onChange, value}}) => (
              <CodeTextInput
                onPress={handleSendVerificationCode}
                maxLength={6}
                left="Safety"
                placeholder={t('password.accountPlaceholder3', {
                  defaultValue: '请输入验证码',
                })}
                i18n={{
                  sendText: t('common.code.send', {
                    defaultValue: '发送验证码',
                  }),
                  resendTemplate: '{seconds}',
                }}
                buttonStyle={{
                  borderRadius: 6,
                }}
                value={value}
                onChangeText={onChange}
                keyboardType="number-pad"
                autoCapitalize="none"
                btnRef={btnRef}
              />
            )}
          />
          <View className="pt-2 ml-14">
            {errors.code && <ErrorText text={errors.code.message!} />}
          </View>
        </View>
        {/* 新密码输入 */}
        <View style={styles.inputGroup}>
          <Controller
            name="password"
            control={control}
            rules={{
              required: t('login.form.password.placeholder', {
                defaultValue: '请输入密码',
              }),
              pattern: {
                value: /(?=.*[a-z])/,
                message: t('personal.passwordScore'),
              },
              min: {
                value: 6,
                message: t('personal.passwordScore'),
              },
            }}
            render={({field: {onChange, value}}) => (
              <TextInput
                left="password"
                placeholder={t('login.form.password.placeholder', {
                  defaultValue: '请输入密码',
                })}
                value={value}
                onChangeText={onChange}
                label={t('datasourceconf.password', {defaultValue: '密码'})}
                secureTextEntry={!showNewPassword}
                right={
                  <Icon
                    size={16}
                    name={showNewPassword ? 'eye' : 'eye-off'}
                    onPress={() => setShowNewPassword(!showNewPassword)}
                  />
                }
              />
            )}
          />
          <View className="pt-2 ml-14">
            {errors.password && <ErrorText text={errors.password.message!} />}
          </View>
        </View>

        {/* 确认密码输入 */}
        <View style={styles.inputGroup}>
          <Controller
            name="confirmPassword"
            control={control}
            rules={{
              required: t('common.password.newpassword.tip3', {
                defaultValue: '请再次输入密码',
              }),
              validate: value =>
                value === password ||
                t('personal.passwordRule', {
                  defaultValue: '两次输入的密码不一致',
                }),
            }}
            render={({field: {onChange, value}}) => (
              <TextInput
                left="repassword"
                placeholder={t('common.password.newpassword.tip3', {
                  defaultValue: '请再次输入密码',
                })}
                value={value}
                onChangeText={onChange}
                secureTextEntry={!showConfirmPassword}
                right={
                  <Icon
                    size={16}
                    name={showConfirmPassword ? 'eye' : 'eye-off'}
                    onPress={() => setShowConfirmPassword(!showConfirmPassword)}
                  />
                }
              />
            )}
          />
          <View className="pt-2 ml-14">
            {errors.confirmPassword && (
              <ErrorText text={errors.confirmPassword.message!} />
            )}
          </View>
        </View>

        {/* 确认按钮 */}
      </ScrollView>
      <Button
        loading={loading}
        disabled={loading}
        title={t('dytable.submit')}
        onPress={handleSubmit(handleResetPassword)}></Button>
    </View>
  );
};

const styles = StyleSheet.create({
  inputGroup: {
    marginBottom: 14,
  },
});

export default ResetPasswordScreen;
